if (typeof jQuery === 'undefined') {
	throw new Error("JSCalculator requires jQuery");
}
(function() {
	'use strict';

	function isOp(input) {
		return input == '+' || input == '-' || input == '*' || input == '/' || input == '=';
	}

	function Calculator(jquery) {
		this._jquery = jquery;
		this._init();
	}

	Calculator.prototype._init = function() {
		this._result = 0;
		this._temp = '';
		this._op = '=';
		this._disp = $('<td colspan="4" class="text-right"></td>');
		this._initPanel();
	}

	Calculator.prototype._reactToInput = function(input) {
		if (!isOp(input)) {
			this._temp += input;
			this._disp.text(this._temp);
		} else {
			var tempFloat = this._temp == '' ? 0 : parseFloat(this._temp);
			switch (this._op) {
				case '+':
					this._result += tempFloat;
					break;
				case '-':
					this._result -= tempFloat;
					break;
				case '*':
					this._result *= tempFloat;
					break;
				case '/':
					this._result /= tempFloat;
					break;
				case '=':
					this._result = tempFloat;
					break;
			}
			this._op = input;
			this._temp = '';
			this._disp.text(this._result);
		}
	}
	Calculator.prototype._initPanel = function() {
		this._panel = $('<div class="calculator-wrapper"></div>');
		var table = $('<table></table>'),
			thead = $('<thead></thead>'),
			tbody = $('<tbody></tbody>'),
			dispRow = $('<tr></tr>'),
			btnRow1 = $('<tr></tr>'),
			btnRow2 = $('<tr></tr>'),
			btnRow3 = $('<tr></tr>'),
			btnRow4 = $('<tr></tr>');
		this._disp.text(this._result).appendTo(dispRow);
		thead.append(dispRow).appendTo(table);
		var btnTd = function(calculator, input) {
			var td = $('<td></td>');
			td.append(new PanelButton(calculator, input));
			return td;
		}
		btnRow1.append(new btnTd(this, '7'))
			.append(new btnTd(this, '8'))
			.append(new btnTd(this, '9'))
			.append(new btnTd(this, '/'))
			.appendTo(table);

		btnRow2.append(new btnTd(this, '4'))
			.append(new btnTd(this, '5'))
			.append(new btnTd(this, '6'))
			.append(new btnTd(this, '*'))
			.appendTo(table);


		btnRow3.append(new btnTd(this, '1'))
			.append(new btnTd(this, '2'))
			.append(new btnTd(this, '3'))
			.append(new btnTd(this, '-'))
			.appendTo(table);


		btnRow4.append(new btnTd(this, '0'))
			.append(new btnTd(this, '.'))
			.append(new btnTd(this, '='))
			.append(new btnTd(this, '+'))
			.appendTo(table);
		this._panel.append(table).appendTo(this._jquery);
	}

	function PanelButton(calculator, input) {
		this._root = calculator;
		this._input = input;
		this._init();
		return this._el;
	}

	PanelButton.prototype._init = function() {
		this._el = $('<button class="btn btn-default"></button>');
		this._el.text(this._input);
		this._initEvents();
	}

	PanelButton.prototype._initEvents = function() {
		var root = this._root,
			input = this._input;
		this._el.click(function() {
			root._reactToInput(input);
		});
	}

	$.prototype.calculator = function() {
		return new Calculator(this);
	}
})();